/**
 * Copyright (c) 2013 onionframework.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.onionframework.persistence.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.orm.hibernate4.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 用于Dao测试的父类
 * 
 * 由于Dao上没有事务拦截，所以SessionFactory的currentSession也是null，
 * 这里需要再测试开始的时候打开一个session，并绑定到线程，测试完成后关闭
 * 
 * @author allan
 *
 */
public class DaoTestCase {

	@Autowired private SessionFactory sessionFactory;
	
	@Before
    public void setUp() throws Exception {
        Session session = getSession(this.sessionFactory);
        TransactionSynchronizationManager.bindResource(sessionFactory,new SessionHolder(session));
    }

    @After
    public void tearDown() throws Exception {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
        closeSession(sessionHolder.getSession(), sessionFactory);
    }

    protected void closeSession(Session session, SessionFactory sessionFactory) {
        SessionFactoryUtils.closeSession(session);
    }

    protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
        Session session = this.sessionFactory.openSession();
        return session;
    }
	
}
